<?php
/**
 * curl
 * -F grant_type=client_credentials
 * -F client_id=<app_id>
 * -F client_secret=<app_secret>
 * -k
 * https://graph.facebook.com/oauth/access_token
 * 
 * Response: "access_token=286811277465|E8jNrZbUUGK41-kVIy3FStK9wPk"
 */
include_once './config.php';
include_once './log4php/Logger.php';

date_default_timezone_set('UTC');

// initialize logging
Logger::configure('./log4j.properties');

$log = Logger::getLogger(basename(__FILE__));
$log->debug('[START] ' . basename(__FILE__));

$post_data = array(
    'client_id' => APP_ID,
    'client_secret' => APP_SECRET,
    'grant_type' => 'client_credentials');

// create a new cURL resource
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);    # required for https urls
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/oauth/access_token');
$response = curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);

// OK response: "access_token=<access_token>"
// OK response_array = {[0] => 'access_token', [1] => '<access_token>'}
$response_array = explode('=', $response);
if (count($response_array)!=2 || $response_array[0] != 'access_token') {
    $log->error("Wrong access_token response: $response");
    $log->debug('[ END ] ' . basename(__FILE__));
    exit ();
}
else {
    $log->info("access_token got successfuly.");
    $access_token = $response_array[1];
}

/*
 * curl
 * -F object=user
 * -F fields=name,pic,pic_square,friends
 * -F verify_token=<verify_token>
 * -F callback_url=http://emmerichgn.facebook.joyent.us/realtime_callback.php
 * http://graph.facebook.com/<APP_ID>/subscriptions?access_token=<access_token>
 */
$callback_url = HOME_ROOT_URL . '/realtime_callback.php';
$log->debug("callback_url = " . $callback_url);

$post_data = array(
    'object' => 'user',
    'fields' => 'name,pic,pic_square,friends',
    'verify_token' => REALTIME_VERIFY_TOKEN,
    'callback_url' => $callback_url);
$url = 'https://graph.facebook.com/' . APP_ID . '/subscriptions?access_token=' . $access_token;

// create a new cURL resource
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);    # required for https urls
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_URL, $url);
$response = curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);

$log->debug("Subscription response: " . $response);


$log->debug('[ END ] ' . basename(__FILE__));

?>
